#include "comm.hpp"
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>

int main()
{
    int shmid = shared_mem().shm_creat(); //新建共享内存

    char* shmAddress = (char*)shmat(shmid, nullptr, 0); //attach共享内存

    FIFO fifo; //利用管道实现共享内存通信的进程之间的协同
    int fd = open(fifo.getFifoName(), O_WRONLY); //会等待写端进程open管道，否则阻塞
    if(fd < 0) { log(FATAL, "%s:%d:open fifo err", __FILE__, __LINE__); exit(1); }
    
    struct shmid_ds shm_ds;
    shmctl(shmid, IPC_STAT, &shm_ds); //获取共享内存的属性信息
    std::cout << "shared memory ds-> " << std::endl;
    printf("__key: 0x%x\n", shm_ds.shm_perm.__key);
    std::cout << "segment size: " << shm_ds.shm_segsz << std::endl;
    std::cout << "creator: " << shm_ds.shm_cpid << std::endl;
    std::cout << "numbers of attch: " << shm_ds.shm_nattch << std::endl;

    std::string msg;
    int cnt = 5;
    while(cnt--)
    {
        std::cout << "please enter@ ";
        std::getline(std::cin, msg);
        memcpy(shmAddress, msg.c_str(), 1024);
        char c = 'c';
        ssize_t s = write(fd, &c, 1); //告诉对方进程，写入完毕，使对方进程结束read的阻塞
        if(s < 0) { log(FATAL, "process a:write err"); exit(1); }
    }
    shmdt(shmAddress); //deattch共享内存
    shmctl(shmid, IPC_RMID, nullptr); //释放共享内存
    return 0;
}